import { boot } from 'quasar/wrappers'
import axios from 'axios'
import { ElNotification, ElLoading } from "element-plus";
import { TokenKey } from 'src/common/const';
import { useUserData } from 'src/hooks';

let loading = null
const Error_Default = '未知错误，请稍后重试'
// 创建一个新的 Axios 实例
const api = axios.create({
  // baseURL: 'http://api.example.com', // API 服务器的 URL
  baseURL: '/api',
  timeout: 15000, // 超时设置（单位：ms）
});

// 添加请求拦截器
api.interceptors.request.use(config => {
  loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  // 在发送请求之前做些什么
  // config.headers = {
  //   'Content-Type': 'application/x-www-form-urlencoded' //配置请求头
  // }
  const [ userData ] = useUserData()
  if (userData[TokenKey]) {
    //携带token到axios参数
    config.headers.Authorization = userData[TokenKey];
    config.headers[TokenKey] = userData[TokenKey];
  }
  return config;
}, error => {
  // 处理请求错误
  console.error('Request Error: ', error);
  ElNotification({
    message: error.msg || Error_Default,
    type: 'error'
  })
  Promise.reject(error);
});

// 添加响应拦截器
api.interceptors.response.use(response => {
  loading && loading.close();
  const { data, config } = response;
  if (data && data.code !== 0 && config.url !== '/agency/jigou/list') {
    const tipType = `${data.code}` === '-1' ? 'info' : 'error'
    ElNotification({
      message: data.msg || Error_Default,
      type: tipType
    })
  }
  return data
}, error => {
  loading && loading.close();
  // 处理响应错误
  console.error('Response Error: ', error);
  ElNotification({
    message: error.message || Error_Default,
    type: 'error'
  })
  Promise.reject(error);
});

export default boot(({ app }) => {
  // for use inside Vue files (Options API) through this.$axios and this.$api

  app.config.globalProperties.$axios = axios
  // ^ ^ ^ this will allow you to use this.$axios (for Vue Options API form)
  //       so you won't necessarily have to import axios in each vue file

  app.config.globalProperties.$api = api
  // ^ ^ ^ this will allow you to use this.$api (for Vue Options API form)
  //       so you can easily perform requests against your app's API
})

export { api }
